package com.ruibo.tax.model.base;

import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description: 生成数据包编号
 * @author: 孙 峰
 * @time: 2020/10/14 18:06
 */
@Component
public class PackageNumber {
    private static AtomicInteger packageNumberCount;


    private static LocalDate localDate;

    public PackageNumber() {
        localDate = LocalDate.now();
        packageNumberCount = new AtomicInteger(0);
    }

    public String getPackageID() {

        DecimalFormat decimalFormat = new DecimalFormat("00000000");
        int packageNumber = 0;
        LocalDate now = LocalDate.now();
        if (localDate.isEqual(now)) {
            packageNumber = packageNumberCount.incrementAndGet();
        } else {
            packageNumberCount = new AtomicInteger(0);
            localDate = LocalDate.now();
        }

        return decimalFormat.format(packageNumber);
    }

    /**
     * 测试
     *
     * @param args
     */
    public static void main(String[] args) {
        PackageNumber packageNumber = new PackageNumber();
        //测试线程执行保证原子性
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 100; i++) {
            Thread thread = new Thread(() -> {
                System.out.println(packageNumber.getPackageID());
            });
            executorService.submit(thread);
        }
        executorService.shutdown();
    }

}
